package com.dlc.shop.poly.common.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.linchuang.seneca.request.PolyMallCommonGetOrderTraceRequest;
import com.linchuang.seneca.response.PolyMallGetOrderTraceResponse;
import com.dlc.shop.common.poly.PolyRouteorderMp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.*;

import java.util.zip.GZIPInputStream;

import static com.linchuang.seneca.utils.ExceptionUtils.getRunException;


/**
 * 后台调用Controller 接口
 */
public class SentURL {
    private static Logger logger = LoggerFactory.getLogger(SentURL.class);
    /**
     * 接口调用 GET
     */
    public static String httpURLConectionGET(String GET_URL) {
        StringBuilder sb = new StringBuilder();
        try {
            URL url = new URL(GET_URL);    // 把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
            connection.setRequestProperty("Accept", "application/json; charset=utf-8");
            connection.connect();// 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;

            while ((line = br.readLine()) != null) {// 循环读取流
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接

        } catch (Exception e) {

            logger.info("调用接口失败："+ getRunException(e));
        }
        return sb.toString();
    }

    public static String sendGet(String url, String param) throws UnsupportedEncodingException {
        StringBuffer stringBuffer = new StringBuffer();
        String urlNameString = "";
        try {
            if(param != null){
                 urlNameString = url + "?" + param;
            }else{
                urlNameString = url;
            }

            logger.info("中国天气网调用接口数据：");
            URL realUrl = new URL(urlNameString);

            HttpURLConnection httpURLConnection = (HttpURLConnection) realUrl.openConnection();
            //在这里设置一些属性，详细见UrlConnection文档，HttpURLConnection是UrlConnection的子类
            //设置连接超时为5秒
            httpURLConnection.setConnectTimeout(5000);
            //设定请求方式(默认为get)
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setRequestProperty("accept", "*/*");
            httpURLConnection.setRequestProperty("Accept-Charset", "UTF-8");
            httpURLConnection.setRequestProperty("contentType", "UTF-8");
            httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");

            //建立到远程对象的实际连接
            httpURLConnection.connect();
            GZIPInputStream gZIPInputStream = null;
            String encoding = httpURLConnection.getContentEncoding();
            if(encoding != null && encoding.equals("gzip")){
                gZIPInputStream = new GZIPInputStream(httpURLConnection.getInputStream());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gZIPInputStream));
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    //转化为UTF-8的编码格式

                    line = new String(line.getBytes("UTF-8"));
                    stringBuffer.append(line);
                }
                bufferedReader.close();
            }else{
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    //转化为UTF-8的编码格式
                    line = new String(line.getBytes("UTF-8"));
                    stringBuffer.append(line);
                }
                bufferedReader.close();
            }
            //返回打开连接读取的输入流，输入流转化为StringBuffer类型，这一套流程要记住，常用
            httpURLConnection.disconnect();
        } catch (MalformedURLException e) {
            logger.info(getRunException(e));
        } catch (IOException e) {
            logger.info(getRunException(e));
        }
        String encoding = getEncoding(stringBuffer.toString());
        logger.info("天气返回数据编码格式为："+ encoding);
        //编码格式

        //String tianqi = changeCharset.changeCharset(stringBuffer.toString(),encoding, "UTF-8");
        return stringBuffer.toString();
    }
    //判断字符串的编码格式
    public static String getEncoding(String str) {
        String encode = "GB2312";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s = encode;
                return s;
            }
        } catch (Exception exception) {
        }

        encode = "ISO-8859-1";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s1 = encode;
                return s1;
            }
        } catch (Exception exception1) {
        }

        encode = "UTF-8";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s2 = encode;
                return s2;
            }
        } catch (Exception exception2) {
        }

        encode = "GBK";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s3 = encode;
                return s3;
            }
        } catch (Exception exception3) {
        }
        return "";
    }


    public static void main(String[] args) {
        //调用接口
        String url = "https://restapi.amap.com/v3/weather/weatherInfo?city=130100&key=908ee9d0fe9d6c34c8ce21496b933ee5&extensions=all";
        //String url = "http://10.4.110.18:8080/yjzbpt/paibanguanli/queryPbryListJSON?startDate="+startdutyDate+"&endDate="+enddutyDate;
        System.out.println(url);
        String data = SentURL.httpURLConectionGET(url);
        System.out.println(data);
    }

    /**
     * 接口调用  POST
     */
    public static PolyMallGetOrderTraceResponse httpURLConnectionPOST(PolyRouteorderMp polyRouteorder, PolyMallCommonGetOrderTraceRequest polyMallCommonGetOrderTraceRequest) {
        try {

            String POST_URL = polyRouteorder.getUrl();

            String method = polyRouteorder.getMethod();
            String platid = polyRouteorder.getPlatid();
            String version = polyRouteorder.getVersion();
            String bizcontent = polyMallCommonGetOrderTraceRequest.getBizcontent();
            String appkey = polyMallCommonGetOrderTraceRequest.getAppkey();
            String appSecret = polyMallCommonGetOrderTraceRequest.getAppSecret();
            String sign = polyMallCommonGetOrderTraceRequest.getSign();
            String token = polyMallCommonGetOrderTraceRequest.getToken();
            String contentType = polyMallCommonGetOrderTraceRequest.getContentType();
            String timestamp = polyMallCommonGetOrderTraceRequest.getTimestamp();
            String param = new StringBuffer()
                    .append("appkey=").append(appkey)
                    .append("&bizcontent=").append(bizcontent)
                    .append("&contenttype=").append(contentType)
                    .append("&method").append(method)
                    .append("&platid=").append(platid)
                    .append("&sign=").append(sign)
                    .append("&timestamp=").append(timestamp)
                    .append("&token=").append(token)
                    .append("&version=").append(version).toString();

            URL url = new URL(POST_URL);

            // 将url以open方法返回的urlConnection连接强转为HttpURLConnection连接(标识一个url所引用的远程对象连接)
            // 此时cnnection只是为一个连接对象,待连接中
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)
            connection.setDoOutput(true);

            // 设置连接输入流为true
            connection.setDoInput(true);

            // 设置请求方式为post
            connection.setRequestMethod("POST");

            // post请求缓存设为false
            connection.setUseCaches(false);

            // 设置该HttpURLConnection实例是否自动执行重定向
            connection.setInstanceFollowRedirects(true);

            // 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)
            // application/x-javascript text/xml->xml数据
            //　application/x-javascript->json对象
            //　application/x-www-form-urlencoded->表单数据
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
            connection.connect();

            // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)
            DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
            //URLEncoder.encode()方法 为字符串进行编码(具体编码格式依据项目文档而定)

            // 将参数输出到连接
            dataout.writeBytes(param);
            // 输出完成后刷新并关闭流
            dataout.flush();
            dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)

            logger.info("调用物流轨迹："+connection.getResponseCode());

            // 连接发起请求,处理服务器响应  (从连接获取到输入流并包装为bufferedReader)
            BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder(); // 用来存储响应数据

            // 循环读取流,若不到结尾处
            while ((line = bf.readLine()) != null) {
                sb.append(bf.readLine());
            }
            bf.close();    // 重要且易忽略步骤 (关闭流,切记!)
            connection.disconnect(); // 销毁连接
            logger.info("调用物流轨迹成功："+sb.toString());
            JSONObject jsonObject = JSON.parseObject(sb.toString());
            return JSON.toJavaObject(jsonObject, PolyMallGetOrderTraceResponse.class);

        } catch (Exception e) {
            logger.info("调用物流轨迹失败："+ getRunException(e));
            return null;
        }
    }

//    public static void main(String[] args) {
//        try {
//            String s = sendGet("http://t.weather.sojson.com/api/weather/city/101090101",null);
//            logger.info("天气数据: " + s);
//        } catch (Exception e) {
//            logger.info("天气数据查询失败：" + getRunException(e));
//        }
//    }e
}


